package com.geekcoding.geekoj.controller;

import com.geekcoding.common.dto.ApiResponse;
import com.geekcoding.geekoj.constant.CommonConstants;
import com.geekcoding.geekoj.dto.User;
import com.geekcoding.geekoj.dto.request.UserChangePwdReq;
import com.geekcoding.geekoj.dto.request.UserSaveOrUpdateReq;
import com.geekcoding.geekoj.repository.UserEntityRepository;
import com.geekcoding.geekoj.service.UserService;
import com.geekcoding.geekoj.utils.JWTUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.springframework.web.bind.annotation.*;

@RestController()
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class UserController {

    private final UserEntityRepository userEntityRepository;

    private final UserService userService;

    @PostMapping("/saveOrUpdate")
    public ApiResponse saveOrUpdate(@RequestBody UserSaveOrUpdateReq rpo) {
        userService.checkUser(rpo.getId());
        return ApiResponse.success(userEntityRepository.convert(userEntityRepository.addOrUpdate(rpo)));
    }

    @PostMapping("/changePassword")
    public ApiResponse changePassword(@RequestBody UserChangePwdReq rpo) {
        val userEntity = userService.currentUser();
        userEntityRepository.changePassword(rpo, userEntity);
        return ApiResponse.success(true);
    }

    @PostMapping("/currentUser")
    public ApiResponse currentUser(HttpServletResponse response){
        val userEntity = userService.currentUser();
        String token = JWTUtils.creatJWT(userEntity);
        response.setHeader(CommonConstants.TOKEN, token);
        return ApiResponse.success(User.of(userEntity, token));
    }
}
